package cn.virens.util.poi.write;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.util.poi.common.ReadCellUtil;
import cn.virens.util.poi.write.tpl.CellTpl;
import cn.virens.util.poi.write.tpl.RowTpl;

public class WriteExcel {
	private Logger logger = LoggerFactory.getLogger(WriteExcel.class);
	private static final String SUFFIX = ".xlsx";
	private String tplPath; // 模板路径
	private String outPath;// 输出路径
	private int tplRow;// 模板所在行
	private List<Object> list = new ArrayList<>();

	public WriteExcel(String tplPath, int tplRow, String outPath) {
		this.tplPath = tplPath;
		this.outPath = outPath;
		this.tplRow = tplRow;
	}

	public List<Object> getData() {
		return list;
	}

	public void addData(Object list) {
		this.list.add(list);
	}

	public void addDatas(List<Object> list) {
		this.list.addAll(list);
	}

	public void write() throws IOException {
		XSSFWorkbook workbook = getWorkbook();
		RowTpl tpl = getTpl(workbook);
	}

	private XSSFWorkbook getWorkbook() throws IOException {
		return new XSSFWorkbook(tplPath);
	}

	private RowTpl getTpl(XSSFWorkbook sxssfWorkbook) {
		RowTpl tpl = new RowTpl();

		XSSFSheet xssfSheet = sxssfWorkbook.getSheetAt(0);

		XSSFRow xssfRow = xssfSheet.getRow(tplRow);

		tpl.setStyle(xssfRow.getRowStyle());// 设置行样式
		tpl.setCellNum(xssfRow.getPhysicalNumberOfCells());// 总列数
		for (int i = 0; i < xssfRow.getLastCellNum(); i++) {
			CellTpl tpl2 = new CellTpl(i);// 创建单元格

			tpl2.setKey(ReadCellUtil.getString(xssfRow, i));// 添加单元格字段
			tpl2.setStyle(xssfRow.getCell(i).getCellStyle());// 设置单元格样式

			tpl.addCell(tpl2);// 将单元格添加到模板内
		}
		xssfSheet.removeRow(xssfRow);// 移除模板行
		return tpl;
	}
}
